package de.tudarmstadt.ukp.muip.fibqdojo.io.raw;

import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.collect.Lists;

import de.tudarmstadt.ukp.muip.fibqdojo.SentenceToken;
import de.tudarmstadt.ukp.muip.fibqdojo.Token;
import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQSentenceToken;
import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQToken;

public class TokenReader extends AbstractTokenReader {

    public TokenReader(Node xmlSentence) {
        super(xmlSentence);
    }

    @Override
    public List<IFIBQSentenceToken> processSentence() {
        NodeList childNodes = xmlSentence.getChildNodes();
        List<IFIBQToken> loadedTokens = loadTokenInformation(childNodes);
        return wrapAsSentenceToken(loadedTokens);
    }

    private List<IFIBQSentenceToken> wrapAsSentenceToken(List<IFIBQToken> loadedTokens) {
        List<IFIBQSentenceToken> sentenceTokens = Lists.newArrayList();
        for (int i = 0; i < loadedTokens.size(); i++) {
            sentenceTokens.add(new SentenceToken(loadedTokens.get(i), i));
        }
        return sentenceTokens;
    }

    private List<IFIBQToken> loadTokenInformation(NodeList childNodes) {
        List<IFIBQToken> tokens = Lists.newArrayList();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (!isElementNode(item)) {
                continue;
            }
            Element element = (Element) item;
            if (element.getNodeName().equals(TOKEN)) {
                tokens.add(processToken(element));
            }
        }
        return tokens;
    }

    protected IFIBQToken processToken(Element parent) {

        String form = "";
        String lemma = "";
        String pos = "";

        NodeList childNodes = parent.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (!isElementNode(item)) {
                continue;
            }
            Element element = (Element) item;
            if (isNodeNameEqualTo(element, FORM)) {
                form = element.getFirstChild().getNodeValue();
            } else if (isNodeNameEqualTo(element, LEMMA)) {
                lemma = element.getFirstChild().getNodeValue();
            } else if (isNodeNameEqualTo(element, POS)) {
                pos = element.getFirstChild().getNodeValue();
            }
        }

        Token token = new Token(form);
        token.setLemma(lemma);
        token.setPartOfSpeech(pos);
        return token;
    }

}
